package io.wongd.lib_douyin.util

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.media.MediaScannerConnection
import android.media.MediaScannerConnection.MediaScannerConnectionClient
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.core.content.ContextCompat.startActivity
import io.wongxd.solution.util.FileUtilW
import java.io.File


object OpenPic {

    fun open(context: Context, file: File?): Boolean {
        file ?: return false
        val intent = Intent(Intent.ACTION_VIEW)
        intent.putExtra("oneshot", 0)
        intent.putExtra("configchange", 0)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
            val contentUri = FileUtilW.getFileUri(context, file.absolutePath)
            intent.setDataAndType(contentUri, "image/*")
        } else {
            intent.setDataAndType(Uri.fromFile(file), "image/*")
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        }
        context.startActivity(intent)
        return true
    }

    /**
     * 转换 content:// uri
     *
     * @param imageFile
     * @return
     */
    fun getImageContentUri(context: Context, imageFile: File): Uri? {
        val filePath = imageFile.absolutePath
        val cursor: Cursor? = context.contentResolver.query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, arrayOf<String>(MediaStore.Images.Media._ID),
            MediaStore.Images.Media.DATA + "=? ", arrayOf<String>(filePath), null
        )
        return cursor?.use {
            if (cursor.moveToFirst()) {
                val id = cursor.getInt(maxOf(0, cursor.getColumnIndex(MediaStore.MediaColumns._ID)))
                val baseUri = Uri.parse("content://media/external/images/media")
                Uri.withAppendedPath(baseUri, "" + id)
            } else {
                if (imageFile.exists()) {
                    val values = ContentValues()
                    values.put(MediaStore.Images.Media.DATA, filePath)
                    context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
                } else {
                    null
                }
            }
        }
    }

    fun openPhoto(context: Context, file: File?) {
        file ?: return
        //这里的file是获取你指定的一张图片的路径
        val intent = Intent()
        intent.action = Intent.ACTION_VIEW
//        intent.setDataAndType(getImageContentUri(context,file), "image/*")
        intent.data = FileUtilW.getFileUri(context, file.path)
//        intent.type = "image/*"
        context.startActivity(intent)
    }

    /**
     * 打开系统相册并浏览指定的目录下的所有图片
     *
     * @param path 这里path就是传的需要浏览指定的文件夹的路径
     */
    fun openPathPhoto(context: Context, path: String?): Boolean {
        var resultFlag = false
        path ?: return resultFlag
        val file = File(path)
        if (file.exists() && file.listFiles().isNullOrEmpty().not()) {
            //  String path= getSDPath() + "/Pictures/PDF原图"
            PictureScanner(context, path)
            resultFlag = true
        }
        return resultFlag
    }

}

internal class PictureScanner(context: Context, pictureFolderPath: String) : MediaScannerConnectionClient {
    private val mMs: MediaScannerConnection
    private val mFile: File
    private val context: Context
    var allFiles: Array<File>

    init {
        val folder = File(pictureFolderPath)
        allFiles = folder.listFiles() ?: arrayOf()
        if (allFiles.isNotEmpty()) {
            swap(allFiles)
        }
        this.context = context
        mFile = allFiles[0]
        mMs = MediaScannerConnection(context, this)
        mMs.connect()
    }

    override fun onMediaScannerConnected() {
        mMs.scanFile(mFile.absolutePath, null)
    }

    override fun onScanCompleted(path: String, uri: Uri) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.data = uri
        context.startActivity(intent)
        mMs.disconnect()
    }

    private fun swap(a: Array<File>) {
        val len = a.size
        for (i in 0 until len / 2) {
            val tmp = a[i]
            a[i] = a[len - 1 - i]
            a[len - 1 - i] = tmp
        }
    }
}
